package com.loyal.loyalerp.phone.util;

import org.json.JSONObject;

import com.github.kevinsawicki.http.HttpRequest;

public class RequestUtils {
	private static final String defaultCharset = "utf-8";
	private static final int connectTimeoutInMissecond = 10000;
	private static final int readTimeoutInMissecond = 30000;

	public static String getJsonText(String url, String charset) {
		if (charset == null)
			charset = defaultCharset;
		HttpRequest request = HttpRequest.get(url).connectTimeout(connectTimeoutInMissecond)
				.readTimeout(readTimeoutInMissecond);
		int code = request.code();
		if (code != 200)
			return null;
		String body = request.body(charset);
		request.disconnect();
		return body;
	}

	public static String getJsonText(String url) {
		return getJsonText(url, defaultCharset);
	}

	public static String getFieldFromJsonText(String jsonText, String field) {
		try {
			JSONObject jsonObject = new JSONObject(jsonText);
			String access_token = jsonObject.getString(field);
			return access_token;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}